# @Version        : 1.0
# @Update Time    : 2025/8/29 1:45
# @File           : pool.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息

from typing import Dict

import redis
from redis.connection import ConnectionPool


class RedisConnectionManager:
    """Redis 连接管理器 - 支持连接池"""

    _pools: Dict[str, ConnectionPool] = {}
    _clients: Dict[str, redis.Redis] = {}

    @classmethod
    def create_pool(cls, name: str = "default", **config) -> ConnectionPool:
        """创建 Redis 连接池"""
        if name in cls._pools:
            return cls._pools[name]

        default_config = {
            "host": "localhost",
            "port": 6379,
            "db": 0,
            "max_connections": 20,
            "decode_responses": True,
            "socket_connect_timeout": 5,
            "socket_timeout": 5,
            "socket_keepalive": True,
            "socket_keepalive_options": {},
            "retry_on_timeout": True,
        }
        default_config.update(config)

        pool = ConnectionPool(**default_config)
        cls._pools[name] = pool
        return pool

    @classmethod
    def get_client(cls, name: str = "default") -> redis.Redis:
        """获取 Redis 客户端"""
        if name not in cls._clients:
            if name not in cls._pools:
                cls.create_pool(name)
            cls._clients[name] = redis.Redis(connection_pool=cls._pools[name])

        return cls._clients[name]

    @classmethod
    def close_all(cls):
        """关闭所有连接"""
        for client in cls._clients.values():
            client.close()
        cls._clients.clear()
        cls._pools.clear()
